package com.youlai.system.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.system.converter.TaskConverter;
import com.youlai.system.mapper.SysTaskMapper;
import com.youlai.system.model.entity.SysTask;
import com.youlai.system.model.query.TaskPageQuery;
import com.youlai.system.model.vo.TaskPageVO;
import com.youlai.system.service.SysTaskService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 任务业务处理实现
 */
@Service
@RequiredArgsConstructor
public class SysTaskServiceImpl extends ServiceImpl<SysTaskMapper, SysTask> implements SysTaskService {

    private final TaskConverter taskConverter;

    @Override
    public Page<TaskPageVO> getTaskPage(TaskPageQuery queryParams) {
        // 查询参数
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        String keywords = queryParams.getKeywords();

        LambdaQueryWrapper<SysTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(keywords), SysTask::getContent, keywords);
        if (queryParams.getType() != null) {
            queryWrapper.eq(SysTask::getType, queryParams.getType());
        }

        if (queryParams.getStatus() != null) {
            queryWrapper.eq(SysTask::getStatus, queryParams.getStatus());
        }

        queryWrapper.orderByDesc(SysTask::getUpdateTime);
        //查询数据
        Page<SysTask> categoryPage = this.page(new Page<>(pageNum, pageSize), queryWrapper);
        return taskConverter.entity2Page(categoryPage);
    }

    @Override
    public boolean deleteTasks(String idsStr) {
        Assert.isTrue(StrUtil.isNotBlank(idsStr), "任务删除数据为空");
        //
        List<Long> ids = new ArrayList<>();
        for (String id : idsStr.split(",")) {
            Long parseLong = Long.parseLong(id);
            ids.add(parseLong);
        }

        // 删除任务
        return this.removeByIds(ids);
    }
}
